package com.todofun.business.tuanke.bo;

import java.util.List;

import com.todofun.business.tuanke.vo.Campaign;
import com.todofun.business.tuanke.vo.PublisInfoStatus;
import com.todofun.common.app.BaseService;
import com.todofun.common.app.BusinessException;
import com.todofun.common.util.CommonUtil;

public class CampaignService extends BaseService{
	
	public static final String[] editIgnor = new String[]{"createTime","publishedTime","isPublished","status"};
	
	public void save(Campaign campaign) {
		super.saveVo(campaign);
	}

	public void edit(Campaign campaign) {
		if(idPublished(campaign.getId())) {
			throw new BusinessException("发布之后不可修改");
		}
		updateVo(campaign,editIgnor);
	}

	private boolean idPublished(Long campaignId) {
		Campaign campaign = (Campaign) super.getVoByID(Campaign.class, campaignId);
		if(campaign == null) {
			throw new BusinessException("不存在的活动ID：" + campaignId);
		}
		return campaign.getIsPublished().equals(false);
	}

	public void publishCampaign(Long id) {
		Campaign campaign = (Campaign) super.getVoByID(Campaign.class, id);
		if(campaign == null) {
			throw new BusinessException("不存在的活动ID：" + id);
		}
		campaign.setIsPublished("true");
		campaign.setStatus(PublisInfoStatus.ENABLE);
		campaign.setPublishedTime(CommonUtil.getCurrentTime());
		updateVo(campaign);
	}

	public Campaign getCampaignByID(Long id) {
		Campaign campaign = (Campaign) getVoByID(Campaign.class,id);
		return campaign;
	}

	public List listAllCampaign() {
		String hql = "from Campaign order by status desc,id desc";
		List<Campaign> allCampaign = queryByHQL(hql);
		return allCampaign;
	}
	
	//当前发布的团购
	public List listAllPublisingCampaign() {
		String hql = "from Campaign where isPublished=? and status=? AND enddate >= CURDATE() order by id desc";
		List<Campaign> listAllPublisingCampaign = queryByHQL(hql,"true",PublisInfoStatus.ENABLE);
		return listAllPublisingCampaign;
	}
	
	// 最近一年的往期团购
	public List listAllPublishedCampaign() {
		String hql = "from Campaign where isPublished=? and status=? AND DATEDIFF(enddate,CURDATE())<0 order by id desc";
		List<Campaign> listAllPublisingCampaign = queryByHQL(hql,"true",PublisInfoStatus.ENABLE);
		return listAllPublisingCampaign;
	}
	
	public void delCampaign(Long campaignId) {
		if(idPublished(campaignId)) {
			throw new BusinessException("发布之后不可删除");
		}
		delVoByID(Campaign.class,campaignId);
	}
	
	public void toggleInfo(Long campaignId) {
		if(!idPublished(campaignId))
			throw new BusinessException("请先发布!");
		Campaign campaign = this.getCampaignByID(campaignId);
		String status = campaign.getStatus();
		if(status.equals(PublisInfoStatus.ENABLE)) {
			status = PublisInfoStatus.DISABLE;
		}else if(status.equals(PublisInfoStatus.DISABLE)) {
			status = PublisInfoStatus.ENABLE;
		}
		campaign.setStatus(status);
		campaign.setPublishedTime(CommonUtil.getCurrentTime());
		updateVo(campaign);
	}

}
